<template>
  <div>
    <article class="main-breadcrumb">
      <el-breadcrumb separator="/" class="main-breadcrumb-wrap">
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">工艺设备管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home">工艺设备管理</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="main-breadcrumb-home" @click="crumbsClick">工艺标注</span>
        </el-breadcrumb-item>
        <el-breadcrumb-item v-if="typeDialog">
          <span class="main-breadcrumb-sp">{{ crumbsStatus }}</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </article>
    <div class="nx-content" v-if="!typeDialog">
      <div class="flex-bet">
        <div class="left-title flex">
          <el-button type="primary" @click="handleReturn()">返回工艺设备管理</el-button>
        </div>
        <el-form ref="ruleForm" :inline="true" :model="ruleForm" class="demo-form-inline">
          <el-form-item label="">
            <el-button-group>
              <el-button @click="changeLabelType(0)" :type="ruleForm.type == 0 ? 'primary' : ''">数值标注</el-button>
              <el-button @click="changeLabelType(1)" :type="ruleForm.type == 1 ? 'primary' : ''">开关标注</el-button>
            </el-button-group>
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="ruleForm.coordinateX" placeholder="标注X" disabled></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-input v-model="ruleForm.coordinateY" placeholder="标注Y" disabled></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-select v-model="ruleForm.technologyDeviceParamId" placeholder="请选择工艺参数" @change="paramchange">
              <el-option v-for="item in paramArray" :key="item.id" :label="item.name + '（' + item.code + '）'" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="handleDelete">删除</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button type="" @click="handleRest">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-row>
          <el-col :span="24">
            <div id="myDiv" class="myDiv" @contextmenu.prevent></div>
            <img id="myImg" :src="labelImage" style="width: 100%" @mousedown="getPosition" />
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import { getTechnologyDeviceLabels, saveTechnologyDeviceLabel, delTechnologyDeviceLabel, getTechnologyDeviceParams } from '@/api/technology'

export default {
  components: {},
  // 表格数据
  data() {
    return {
      crumbsStatus: '', // 三级面包屑名称
      typeDialog: false,
      ruleForm: {
        // 表单字段
        id: '',
        coordinateX: '',
        coordinateY: '',
        paramCode: '新标注',
        paramValue: '',
        paramUnit: '',
        type: 0,
        technologyDeviceParamId: '',
        technologyDeviceId: ''
      },
      labelType: 0, // 标注类型
      labelData: [], // 标注数据
      labelImage: '', // 标注图片
      paramArray: [] // 参数数组
    }
  },
  // 初始化加载
  mounted() {
    this.labelImage = this.$route.query.flowChartImage
    // 获取全部工艺参数列表
    this.getTechnologyDeviceParams()
    // 获取全部设备标注列表
    this.getList()
  },
  // 自定义方法
  methods: {
    // 获取全部工艺参数列表
    getTechnologyDeviceParams() {
      getTechnologyDeviceParams({
        id: this.$route.query.technologyDeviceId
      }).then((res) => {
        if (res.code == 200) {
          this.paramArray = res.data
        }
      })
    },
    // 获取全部设备标注列表
    getList() {
      getTechnologyDeviceLabels({
        id: this.$route.query.technologyDeviceId
      }).then((res) => {
        if (res.code == 200) {
          this.labelData = res.data

          // 循环创建新标注
          res.data.forEach((val) => {
            this.createMarker(val.id, val.coordinateX, val.coordinateY, val.paramCode, val.paramValue + '\xa0' + '\xa0' + '\xa0' + val.paramUnit, val.paramValue, val.type, 0)
          })
        }
      })
    },
    // 保存
    handleSave() {
      if (!this.ruleForm.coordinateX || this.ruleForm.coordinateX == '' || !this.ruleForm.coordinateY || this.ruleForm.coordinateY == '') {
        this.$message({
          type: 'error',
          message: '请选择标注'
        })
        return
      }

      if (!this.ruleForm.technologyDeviceParamId || this.ruleForm.technologyDeviceParamId == '') {
        this.$message({
          type: 'error',
          message: '请选择工艺参数'
        })
        return
      }

      this.ruleForm.technologyDeviceId = this.$route.query.technologyDeviceId
      saveTechnologyDeviceLabel(this.ruleForm).then((res) => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
          // 清空标注
          this.clearLabel()

          // 查询
          this.getList()
        }
      })
    },
    // 删除
    handleDelete() {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (this.ruleForm.id != '') {
            delTechnologyDeviceLabel({ id: this.ruleForm.id }).then((res) => {
              if (res.code == 200) {
                this.$message({
                  type: 'success',
                  message: res.msg
                })
              }
            })
          } else {
            this.removeMarker(this.ruleForm.id)
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          }
          setTimeout(() => {
            // 清空标注
            this.clearLabel()

            // 查询
            this.getList()
          }, 200)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置
    handleRest() {
      this.clearLabel()
      this.getList()
    },
    // 面包屑
    crumbsClick() {
      this.typeDialog = false
      this.addEditIsDialog = false
    },
    // 返回
    handleReturn() {
      this.$router.push({
        path: `/technology/technologyDevice`,
        query: {}
      })
    },
    changeLabelType(val) {
      if (this.ruleForm.type != val) {
        this.ruleForm.type = val
      }
    },
    // 参数下拉
    paramchange() {
      var val = this.paramArray.find((item) => {
        return item.id === this.ruleForm.technologyDeviceParamId
      })

      this.ruleForm.paramCode = val.code
      this.ruleForm.paramValue = val.realData
      this.ruleForm.paramUnit = val.unit

      var span = document.getElementById('span' + this.ruleForm.id)
      if (span != undefined || span != null) {
        if (this.type == 0) {
          span.textContent = val.code + '：' + val.realData + val.unit
        } else {
          span.style.width = 12 + 'px'
          span.style.height = 12 + 'px'
          span.style.borderRadius = 50 + '%'
          if (this.ruleForm.paramValue == 0) {
            span.style.backgroundColor = 'red'
          } else if (this.ruleForm.paramValue == 1) {
            span.style.backgroundColor = 'green'
          } else {
            span.style.backgroundColor = 'grey'
          }
        }
      }
    },
    // 清空标注
    clearLabel() {
      // 清空当前标注
      this.ruleForm = {
        // 表单字段
        id: '',
        coordinateX: '',
        coordinateY: '',
        paramCode: '新标注',
        paramValue: '',
        paramUnit: '',
        type: 0,
        technologyDeviceParamId: '',
        technologyDeviceId: ''
      }

      // 清空所有标注
      document.getElementById('myDiv').innerHTML = ''
    },
    // 获取标注位置
    getPosition(e) {
      e = e || window.event

      // 判断是否是左键点击
      if (e.button === 0) {
        // 坐标
        var x = e.offsetX || e.layerX
        var y = e.offsetY || e.layerY

        // 获取图片比例坐标
        var myImg = document.querySelector('#myImg')
        var currWidth = myImg.clientWidth
        var currHeight = myImg.clientHeight
        var ProportionWidthInImg = x / currWidth
        var ProportionHeightInImg = y / currHeight

        // 移除旧标注
        this.removeMarker(this.ruleForm.id)

        // 创建新标注
        this.createMarker(this.ruleForm.id, ProportionWidthInImg, ProportionHeightInImg, this.ruleForm.paramCode, this.ruleForm.paramValue + '\xa0' + '\xa0' + '\xa0' + this.ruleForm.paramUnit, this.ruleForm.paramValue, this.ruleForm.type, 1)

        // 更新标注信息
        this.ruleForm.coordinateX = ProportionWidthInImg
        this.ruleForm.coordinateY = ProportionHeightInImg
      }
    },
    // 移除标注
    removeMarker(id) {
      // 移除图标
      var img = document.getElementById('img' + id)
      if (img) {
        document.getElementById('myDiv').removeChild(img)
      }

      // 移除文字
      var span = document.getElementById('span-name' + id)
      if (span) {
        document.getElementById('myDiv').removeChild(span)
      }
      var span2 = document.getElementById('span-value' + id)
      if (span2) {
        document.getElementById('myDiv').removeChild(span2)
      }
    },
    // 创建标注
    createMarker(id, ProportionWidthInImg, ProportionHeightInImg, text, value, val, labelType, type) {
      if (!ProportionWidthInImg || !ProportionHeightInImg || ProportionWidthInImg === '' || ProportionHeightInImg === '') {
        return
      }

      // 获取图片宽高
      var myImg = document.querySelector('#myImg')
      var currWidth = myImg.clientWidth
      var currHeight = myImg.clientHeight

      // 根据比例坐标计算实际坐标，再加上点位半径
      var x = ProportionWidthInImg * currWidth + document.getElementById('myImg').offsetLeft - 80 / 2
      var y = ProportionHeightInImg * currHeight + document.getElementById('myImg').offsetTop - 80 / 2

      // 文字样式
      var span = document.createElement('span')
      span.id = 'span-name' + id
      span.textContent = text
      span.style.left = x + 8 + 'px'
      span.style.top = y + 1 + 'px'
      span.style.position = 'absolute'
      span.style.zIndex = '99'
      span.style.color = 'white'
      span.style.fontSize = '10px'

      // 文字样式

      var span2 = document.createElement('span')
      span2.id = 'span-value' + id
      if (labelType == 0) {
        span2.textContent = value
        span2.style.left = x + 8 + 'px'
        span2.style.top = y + 13 + 'px'
      } else {
        span2.style.width = 12 + 'px'
        span2.style.height = 12 + 'px'
        span2.style.borderRadius = 50 + '%'
        span2.style.left = x + 12 + 'px'
        span2.style.top = y + 15 + 'px'
        if (val == 0) {
          span2.style.backgroundColor = 'red'
        } else if (val == 1) {
          span2.style.backgroundColor = 'green'
        } else {
          span2.style.backgroundColor = 'grey'
        }
      }
      span2.style.position = 'absolute'
      span2.style.zIndex = '99'
      span2.style.color = 'white'
      span2.style.fontSize = '10px'

      // 加载文字到图片上
      document.getElementById('myDiv').appendChild(span)
      document.getElementById('myDiv').appendChild(span2)

      // 文字1宽度
      var span1Width = document.getElementById('span-name' + id).clientWidth + 20

      // 文字2宽度
      var span2Width = document.getElementById('span-value' + id).clientWidth + 17

      // 点位图片样式
      var img = document.createElement('img')
      img.id = 'img' + id
      img.style.height = '30px'
      img.style.width = (span2Width > span1Width ? span2Width : span1Width) + 'px'
      img.style.left = x + 'px'
      img.style.top = y + 'px'
      img.style.position = 'absolute'
      img.style.zIndex = '99'
      img.style.cursor = 'pointer'
      img.src = type == 0 ? require('@/assets/ybz.png') : require('@/assets/dqbz.png')

      // 添加左键点击事件
      var that = this
      img.onclick = function () {
        if (id == that.ruleForm.id) {
          // 点击当前标注
          return
        }

        // 移除旧标注
        that.removeMarker(that.ruleForm.id)
        if (that.ruleForm.id != '') {
          // 如果旧标注为已标注，恢复原位置
          that.labelData.forEach((val) => {
            if (val.id == that.ruleForm.id) {
              that.createMarker(val.id, val.coordinateX, val.coordinateY, val.paramCode, val.paramValue + '\xa0' + '\xa0' + '\xa0' + val.paramUnit, val.paramValue, val.type, 0)
              return
            }
          })
        }

        // 将选中的标注变成当前标注
        that.labelData.forEach((val) => {
          if (val.id == id) {
            // 每个字段单独赋值，避免影响原数据
            that.ruleForm = {
              id: val.id,
              coordinateX: val.coordinateX,
              coordinateY: val.coordinateY,
              paramCode: val.paramCode,
              paramValue: val.paramValue,
              paramUnit: val.paramUnit,
              type: val.type,
              technologyDeviceParamId: val.technologyDeviceParamId,
              technologyDeviceId: val.technologyDeviceId
            }

            // 更换图标为待标注
            document.getElementById('img' + val.id).src = require('@/assets/dqbz.png')

            return
          }
        })
      }

      // 加载点位到图片上
      document.getElementById('myDiv').appendChild(img)
    }
  }
}
</script>
<style lang="less" scoped>
.main-breadcrumb {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: 76px;
  border-bottom: solid 20px #f2f2f2;
  padding-left: 20px;

  .main-breadcrumb-wrap {
    font-size: 16px;
    line-height: 68px;

    .main-breadcrumb-home {
      cursor: pointer;
      color: #666666;
      font-weight: bold;
    }

    .main-breadcrumb-sp {
      color: #666666;
      font-weight: bold;
    }
  }
}
</style>